package com.tinyseed.hmxx.admin.security.rest;

import cn.hutool.core.codec.Base64;
import com.tinyseed.hmxx.admin.security.AuthInfo;
import com.tinyseed.hmxx.admin.security.domain.AuthUser;
import com.tinyseed.hmxx.admin.security.domain.JwtUser;
import com.tinyseed.hmxx.admin.security.utils.JwtTokenUtil;
import com.tinyseed.hmxx.admin.security.utils.SecurityUtils;
import com.tinyseed.hmxx.common.exception.BadRequestException;
import com.tinyseed.hmxx.common.utils.PasswordUtils;
import com.tinyseed.hmxx.common.utils.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @version Revision 1.0.0
 * @版权：
 * @author: Howard
 * @email:
 * @see:
 * @创建日期：2020/2/22
 * @功能说明：权限rest
 * @begin
 * @修改记录:
 * @修改后版本 修改人        修改内容
 * @2020/2/22 wuxiran        创建
 * @end
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthenticationController {

    private final UserDetailsService userDetailsService;

    private final RSAUtils RSAUtils;

    private final JwtTokenUtil jwtTokenUtil;

    private final PasswordUtils passwordUtils;

    public AuthenticationController(@Qualifier("JwtUserDetailsService") UserDetailsService userDetailsService, RSAUtils RSAUtils, JwtTokenUtil jwtTokenUtil, PasswordUtils passwordUtils) {
        this.userDetailsService = userDetailsService;
        this.RSAUtils = RSAUtils;
        this.jwtTokenUtil = jwtTokenUtil;
        this.passwordUtils = passwordUtils;
    }

    @GetMapping(value = "/publicKey")
    public ResponseEntity<String> publicKey() {

        return ResponseEntity.ok(Base64.encode(RSAUtils.getPublicKey().getEncoded()));
    }

    @PostMapping(value = "/login")
    public ResponseEntity Login(@Validated @RequestBody AuthUser authUser) {
        final JwtUser jwtUser = (JwtUser) userDetailsService.loadUserByUsername(authUser.getUsername());
        String password;
        password = RSAUtils.privateKeyDecypt(authUser.getPassword());

        if (!passwordUtils.matchesPassword(password, jwtUser.getPassword())) {
            throw new BadRequestException("用户或密码错误");
        }
        if (!jwtUser.isEnabled()) {
            throw new BadRequestException("账户已经停用");
        }
        final String token = jwtTokenUtil.generateToken(jwtUser);

        return ResponseEntity.ok(new AuthInfo(token, jwtUser));
    }

    /**
     * (待完善确认功能是否可以使用)
     * Description 获取用户信息
     * Version 1.0
     * Date 2020/2/26 11:10 下午
     * Author howard
     */
    @GetMapping(value = "/info")
    public ResponseEntity getUserInfo() {
        JwtUser jwtUser = (JwtUser) userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
        return ResponseEntity.ok(jwtUser);
    }

}
